#!/bin/bash

BASE_PATH=$HOME/.mara
MYSQL_NAME="sec-mysql"

getSecurity() {
    cat $BASE_PATH/security.json | jq -r "$1"
}

get_secrets() {
  if [ ! -f $BASE_PATH/security.json ]; then
    echo "Please create security.json file first"
    exit 1
  fi

  # mysql root password
  mysql_root_password=$(getSecurity ".mysql.root")
  if [ -z $mysql_root_password ] || [ $mysql_root_password == "null" ]; then
    echo "Not found root password in security.json"
    exit 1
  fi

  # mysql user password
  mysql_user_password=$(getSecurity ".mysql.user")
  if [ -z $mysql_user_password ] || [ $mysql_user_password == "null" ]; then
    echo "Not found user password in security.json"
    exit 1
  fi
}

shellExit()
{
if [ $1 -eq 1 ]; then
    printf "\nfailed!!!\n\n"
    exit 1
fi
}

get_secrets

printf "\nRegenerating file\n\n"
time go run -v ./cmd/mysqlmd/main.go  -addr localhost:3306 -user root -pass $mysql_root_password -name $1
shellExit $?

time go build -o gormgen ./cmd/gormgen/main.go
shellExit $?

if [ ! -d $HOME/go/bin ];then
   mkdir -p $HOME/go/bin
fi

mv gormgen $HOME/go/bin
shellExit $?

printf "\ncreate curd code : \n"
go generate ./...
shellExit $?

printf "\nFormatting code\n\n"
time go run -v ./cmd/mfmt/main.go
shellExit $?

printf "\nDone.\n\n"
